package com.ys.timer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.business.TpAmazonShop;
import com.ys.enume.AmazonSellerEnum;
import com.ys.service.finance.TcwFinancesEventGroupsOpService;
import com.ys.service.log.ApiLogService;
import com.ys.util.RedisUtil;
import com.ys.util.dhecp.DateUtils;
import com.ys.vo.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
public class TimerFinancesEventGroupsOpDaily {
	private static Logger logger = LoggerFactory.getLogger(TimerFinancesEventGroupsOpDaily.class);

	@Autowired
	private ApiLogService apiLogService;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private TcwFinancesEventGroupsOpService tcwFinancesEventGroupsOpService;


	@Scheduled(cron = "0 0 9 * * ?")
	public void getGroupsOp0() throws Exception{
		getGroupsOp(0);
	}

	@Scheduled(cron = "0 0 16 * * ?")
	public void getGroupsOp1() throws Exception{
		getGroupsOp(1);
	}

	public void getGroupsOp(int type) throws Exception{
		logger.info("***********每天定时新增财务目录getGroupsOp，开始***********");

		try {
//			上个月第一天
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DATE, -1);

			calendar.set(Calendar.HOUR_OF_DAY,00);
			calendar.set(Calendar.MINUTE,00);
			calendar.set(Calendar.SECOND,00);

			Date startTime = calendar.getTime();
			String startTimeStr = DateUtils.convertDateToTDate(startTime);

			calendar.set(Calendar.HOUR_OF_DAY,23);
			calendar.set(Calendar.MINUTE,59);
			calendar.set(Calendar.SECOND,59);

			Date endTime = calendar.getTime();
			String endTimeStr = DateUtils.convertDateToTDate(endTime);

			String whereL = "";
			if (type == 0){
				whereL = " AND A.regionCode = 'EUROPE'";
			} else if (type == 1){
				whereL = " AND A.regionCode = 'NORTH'";
			}
			List<Map<String, Object>> tpAmazonSellerList = new TpAmazonSeller()
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = A.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.authorizeState = '已授权'" + whereL)
					.setStatus(1)
					.queryMap();
			for (int i = 0; i < 20; i++) {
				redisUtil.hPut("THREAD_APIOP", String.valueOf(i), "0");
			}
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonSellerList));
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				boolean variable = true;
				while (variable) {
					Map<Object, Object> redisMap = redisUtil.hGetAll("THREAD_APIOP");
					for (Map.Entry<Object, Object> e : redisMap.entrySet()) {
						if (e.getValue().equals("1")) {
							continue;
						} else if (e.getValue().equals("0")) {
							redisUtil.hPut("THREAD_APIOP", String.valueOf(e.getKey()), "1");
//								 开启线程
							Thread t = new Thread(() -> {
								ApiResponse apiResponse = null;
								try {
									apiResponse = tcwFinancesEventGroupsOpService.getGroupsOp(jsonObject, startTimeStr, endTimeStr);
								} catch (Exception exception) {
									exception.printStackTrace();
									redisUtil.hPut("THREAD_APIOP", String.valueOf(e.getKey()), "0");
								}
								if (apiResponse.getCode() == 500) {
									apiLogService.addApiLog("Amazon", "GetGroupsOp", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(jsonObject), "店铺:" + jsonObject.get("sellerName").toString(), apiResponse.getCode(), apiResponse.getMessage());
								}
								logger.info("***********每月定时新增财务目录getGroupsOp，结束***********");
								redisUtil.hPut("THREAD_APIOP", String.valueOf(e.getKey()), "0");
							});
							t.start();
//								Thread.sleep(1000L);
						}
						variable = false;
						break;
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}


}
